<template>
  <div class="gk-layout-container">
    <div class="gk-layout-header">
      <!--工具栏-->
      <div class="toolbar" style="float:left;">
        <el-form :inline="true" :model="filters" :size="global.gSize">
          <el-form-item>
            <el-input v-model="filters.name" :placeholder="$t('item.please enter')"></el-input>
          </el-form-item>



          <el-form-item>
            <kt-button icon="fa fa-search" :label="$t('action.search')" perms="cy:equp:view" type="primary"
              @click="findPage(null)" />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-plus" :label="$t('action.add')" perms="cy:equp:add" type="primary"
              @click="handleAdd" />
          </el-form-item>
        </el-form>
      </div>


      <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
        <el-form :inline="true" :size="global.gSize">
          <el-form-item>
            <el-button-group>
              <el-tooltip content="下载模板" placement="top">
                <el-button icon="fa fa-download" @click="exportExample"></el-button>
              </el-tooltip>

              <el-tooltip content="导出Excel" placement="top">
                <el-button icon="fa fa-file-excel-o" @click="exportExcel" />
              </el-tooltip>
              <el-tooltip content="导入Excel" placement="top">
                <el-button icon="fa fa-upload" @click="importExcel" />
              </el-tooltip>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>

    </div>


    <div class="gk-layout-main">
      <my-table :data="pageResult.content" :loading="loading"  >
        <el-table-column :label="$t('action.desc')" width="50" header-align="center" align="center">
          <template slot-scope="scope"> {{scope.$index+1}} </template>
        </el-table-column>
        <column prop="alias" label="名称"/>
       <column   prop="code" label="条码" />
        <column  prop="custom" label="客户名称" />
        <column  prop="volCoil1" label="启动电压" />
        <column  prop="volCoil2" label="升压" />
    
        <column prop="coilHz" label="频率" />
        <column  prop="tmpFan" label="启动温度"/>
        <column  prop="nextQTime" label="请求时间"/>
        <column prop="offlineTime" label="离线运行" />
        <column prop="canWork" label="可用"  :formatter="selectionFormats"/> 
        <el-table-column header-align="center" align="center" :label="$t('action.operation')" width="150">
          <template slot-scope="scope"> 
            <kt-delete-button   v-if="scope.row.active=='1'" perms="cy:equp:Disable"    @click="handleDisable(scope.$index, scope.row)" />
              
            <kt-button icon="fa fa-edit" label="" perms="cy:equp:edit"    @click="handleEdit(scope.$index, scope.row)" />
      
            <kt-button icon="fa fa-list-ol" label="" perms="cy:equp:edit"    @click="handleOpen(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </my-table>
    </div>
    <!--分页栏-->
    <div class="toolbar gk-layout-footer" style="padding:10px;">
      <el-pagination layout="total, prev, pager, next, jumper" @current-change="findPage"
        :current-page="pageRequest.pageNum" :page-size="pageRequest.pageSize" :total="pageResult.totalSize"
        style="float:right;">
      </el-pagination>
    </div>








    <!-- EXCEL导入 -->
    <upload-file :key="componentKey" :UpLoadFileVisible="UpLoadFileVisible" @ImportExcelData="ImportExcelData"
      @cancel="cancel" :PercentageValue="this.percentageValue"></upload-file>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'设备 — 新增':'设备 — 编辑'" width="80%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="200px" :rules="dataFormRules" ref="dataForm" :size="global.gSize" label-position="right">
           <el-form-item label="ID" prop="id" v-if="false">
                <el-input v-model="dataForm.id" auto-complete="off"></el-input>
            </el-form-item>
         <el-row>
          <el-col :span="12">
            <el-form-item label="编码" prop="code">
              <el-input v-model="dataForm.code" disabled="true"  auto-complete="off"></el-input>
            </el-form-item>
          
          </el-col>
          <el-col :span="12">
              <el-form-item label="别名" prop="alias">
                <el-input v-model="dataForm.alias" auto-complete="off"></el-input>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="允许运行" prop="canWork">
                <el-select v-model="dataForm.canWork" placeholder="请选择" style="width: 100%;" >
                      <el-option v-for="item in dicts.canWork" :key="item.value"   :label="item.label"  :value="item.value">
                      </el-option>
                </el-select>
            </el-form-item>
       
           </el-col>
          <el-col :span="12">
              <el-form-item label="客户" prop="custom">
                <el-input v-model="dataForm.custom" auto-complete="off"></el-input>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="启动电压(130-140)" prop="volCoil1">
              <el-input v-model="dataForm.volCoil1" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="次级电压(10-30)" prop="volCoil2">
              <el-input v-model="dataForm.volCoil2" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作频率(40-65)" prop="coilHz">
              <el-input v-model="dataForm.coilHz" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="风扇启动温度(20-35)" prop="tmpFan">
                <el-input v-model="dataForm.tmpFan" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="查询周期(1-30)" prop="nextQTime">
              <el-input v-model="dataForm.nextQTime" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="离线运行时间(10-255)" prop="offlineTime">
                  <el-input v-model="dataForm.offlineTime" auto-complete="off"></el-input>
                </el-form-item>
          </el-col>
        </el-row>
  
       <el-row> 
          <el-col :span="12">
            <el-form-item label="温度下限(-20--10)" prop="tmpLimitFloor">
                  <el-input v-model="dataForm.tmpLimitFloor" auto-complete="off"></el-input>
                </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="温度上限(40-60)" prop="tmpLimitCeil">
              <el-input v-model="dataForm.tmpLimitCeil" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
  
      <el-row> 
          <el-col :span="12">
            <el-form-item label="电压下限(110--120)" prop="vLimitFloor">
                  <el-input v-model="dataForm.vLimitFloor" auto-complete="off"></el-input>
                </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电压上限(150-160)" prop="vLimitCeil">
              <el-input v-model="dataForm.vLimitCeil" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
  
  <el-row> 
          <el-col :span="12">
            <el-form-item label="电流下限(5--15)" prop="iLimitFloor">
                  <el-input v-model="dataForm.iLimitFloor" auto-complete="off"></el-input>
                </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电流上限(35-45)" prop="iLimitCeil">
              <el-input v-model="dataForm.iLimitCeil" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="global.gSize" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="global.gSize" type="primary" @click.native="submitForm">{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import PopupTreeInput from "@/components/PopupTreeInput"
  import KtDeleteButton from "@/views/Core/KtDeleteButton"
  import KtButton from "@/views/Core/KtButton"
 
  import { format } from "@/utils/datetime"
  import UploadFile from "@/views/Core/UploadFile"
  import { myXlsExport } from "@/excel/myXls"
  import XLSX from "xlsx";
  import MyTable from "@/views/Core/MyTable"
  import Column from "@/views/Core/Column"
  
  export default {
    components: {
      PopupTreeInput,
      MyTable,
      KtButton,KtDeleteButton,
      Column,
      UploadFile
    },

    data() {

      return {
  
        loading: false,
        filters: {
          name: ''
        },
        percentageValue: 0,
        columns: [],
        filterColumns: [],
        pageRequest: { pageNum: 1, pageSize: 20 },
        pageResult: {},
        tableData: [],
        componentKey: 0,
        operation: false, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        UpLoadFileVisible: false,
        editLoading: false,
        dicts: this.$store.state.dict.dicts,
        // 新增编辑界面数据
        dataForm: {
          id: 0,

          orderNo:1
        },
        classTypes: [],
      }
    },

    computed: {
      dataFormRules() {
        const dataFormRules = {
          name: [{ required: true, message: "请输入名称", trigger: 'blur' }],
          
        };
        return dataFormRules;
      }
    },

    methods: {
      //获取分页数据
      findPage: function (data) {

        if (data !== null) {
          this.filters.pageNum = data
        } else {
          this.filters.pageNum = 1
        }
        this.filters.pageSize = this.pageRequest.pageSize
        this.loading = true;
        this.$api.equp.findPage(this.filters).then((res) => {
          this.pageResult = res.data
          this.loading = false;
        }).then(data != null ? data.callback : '')
      },
      // 加载用户角色信息
      findUserRoles: function () {
        this.$api.role.findAll().then((res) => {
          // 加载角色集合
          this.roles = res.data
        })
      },
      importExcel() {
        this.componentKey += 1;
        this.UpLoadFileVisible = true
      },
      ImportExcelData(excelData) {
        // 将上面数据转换成 table需要的数据
        let arr = [];
        excelData.forEach(item => {
          let obj = {};
          obj.name = item["名称"];
          obj.classifyId = this.classTypeToId(item["类别名称"]);
          obj.coreItemType = this.dicToId(item["物料类型"]);
          obj.code = item["编码"];
          obj.modelSpecs = item["规格型号"];
          obj.packageSpecs = item["包装规格"];
          arr.push(obj);
          this.percentageValue = Math.round(this.percentageValue + 100 / excelData.length)
          // this.$api.item.save(obj).then((res) => {
          //     if(res.code==200){
         
          //         this.percentageValue= this.percentageValue+100/excelData.length
          //     }
          //     else
          //     {
          //         this.percentageValue=0
          //     }
          // })
        });
        this.$api.item.ImportList(arr).then((res) => {
          if (res.code == 200) {
            this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
            this.UpLoadFileVisible = false
            this.findPage(null)
            this.percentageValue = 0
          }
          else {
            this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
            this.UpLoadFileVisible = false
            this.percentageValue = 0
          }

        })


      },
      cancel: function () {
        this.UpLoadFileVisible = false;
        this.percentageValue = 0
      },
      //导出的方法
      exportExcel() {
      
 
        this.$api.item.GetExportList(this.filters).then((res) => {
          const tHeader = ['名称', '类别名称', '物料类型', '编码', '规格型号', '包装规格'];
          const filterVal = ['name', 'classifyName', 'coreItemTypeName', 'code', 'modelSpecs', 'packageSpecs'];
          myXlsExport(tHeader, filterVal ,res.data, '物料信息导出');
        })
      
      },
      
      //下载模板
      exportExample() {
            const tHeader = ['名称', '类别名称', '物料类型', '编码', '规格型号', '包装规格'];
            const filterVal = ['name', 'classifyName', 'coreItemTypeName', 'code', 'modelSpecs', 'packageSpecs'];
            myXlsExport(tHeader, filterVal ,[], '物料信息模板');

      },
      // 批量删除
      handleDelete: function (data) {
        this.$api.item.batchDelete(data.params).then(data != null ? data.callback : '')
      },
      // 显示新增界面
      handleAdd: function () {

        this.dialogVisible = true
        this.operation = true
        this.dataForm = {

        }
      },
      selectionFormats: function (row, column, cellValue, index) {
       let key  = column.property; 
        let dict = this.dicts[key];
        if (dict == undefined) {
          return row[column.property]
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].value == cellValue) {
            return dict[i].label;
          }
        }
        return row[column.property]
      },

 // 显示编辑界面
      handleOpen: function (index, row) {
        window.open ('static/cy/detail.htm?'+ row.code+"_"+row.alias)
      },

      // 显示编辑界面
      handleEdit: function (index, row) {

        this.dialogVisible = true
        this.operation = false
        this.dataForm = Object.assign({}, row)
      },
      //取消
      cancelForm: function () {
        if (this.$refs['dataForm'] != undefined) {
          this.$refs['dataForm'].resetFields();
        }

        this.dialogVisible = false
      },
      //新增
      submitForm: function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.$confirm(this.getKey('action.isConfirm'), this.getKey('action.tips'), {}).then(() => {
              this.editLoading = true
              let params = Object.assign({}, this.dataForm)
              this.$api.equp.save(params).then((res) => {
                //this.editLoading = false
                if (res.code == 200) {
                  this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
                  this.dialogVisible = false
                  this.$refs['dataForm'].resetFields()
                } else {
                  this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
                }
                this.findPage(null)
              })
            })
          }
        })
      },
      

    
      handleDisable: function (index, row) {
        this.dataForm = Object.assign({}, row)
        if (this.dataForm.active == "禁用") {
          this.$confirm('你选中的物料已经是禁用状态了', '提示', {
            type: 'warning'
          })
        } else {
          this.dataForm.active = 0;
          this.$api.item.disable(this.dataForm).then((res) => {
            if (res.code == 200) {
              this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
              this.dialogVisible = false
            } else {
              this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
            }
            this.findPage(null)
          })
        }
      },
      // 菜单树选中
      deptTreeCurrentChangeHandle(data, node) {
        this.dataForm.deptId = data.id
        this.dataForm.deptName = data.name
      },
      // 时间格式化
      dateFormat: function (row, column, cellValue, index) {
        return format(row[column.property])
      },
      //加载物料类别分类
      findClassTypes: function () {
        this.$api.classify.findPage().then((res) => {
          this.classTypes = res.data.content
        })
      },
      
      // 处理表格列过滤显示
      handleFilterColumns: function (data) {
        this.filterColumns = data.filterColumns
        this.$refs.tableColumnFilterDialog.setDialogVisible(false)
      },
      getKey: function (arg) {
        return this.$t(arg)
      },


      selectionFormat: function (row, column, cellValue, index) {
        let key = ""
        let propt = column.property;
        let val = row[column.property];
        let dict = this.classTypes;
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].id == val) {
            return dict[i].name;
          }
        }
        return val
      },
      classifyidtype: function (row, column, cellValue, index) {
        let val = parseInt(row["classifyId"]);
        let dict = this.classTypes;
        if (dict == undefined) {
          return row[column.property]
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].id == val) {
            return dict[i].name;
          }
        }
        return row[column.property]
      },
      activeStatusFormat: function (row, column, cellValue, index) {
   

        let dict = this.dicts["itemActive"];
        if (dict == undefined) {
          return cellValue
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].value == cellValue) {
            return dict[i].label;
          }
        }
        return cellValue

      },
      classTypeToId: function (name) {
        let list = this.classTypes;
        for (let i = 0; i < list.length; i++) {
          if (list[i].name == name) {
            return list[i].id;
          }
        }
        return 0
      },

      idToClassType: function (id) {
        let list = this.classTypes;
        for (let i = 0; i < list.length; i++) {
          if (list[i].id == id) {
            return list[i].name;
          }
        }
        return id
      },

      dicToId: function (name) {
        let dict = this.dicts["coreItemType"];
        if (dict == undefined) {
          return 0
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].label == name) {
            return dict[i].value;
          }
        }
        return 0
      },

      idToDic: function (id) {
        let dict = this.dicts["coreItemType"];
        if (dict == undefined) {
          return id
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].value == id) {
            return dict[i].label;
          }
        }
        return id
      },
      selectionFormat1: function (row, column, val, index) {

        //let val=row["isSorting"];
        let dict = this.dicts["itemSorting"];
        if (dict == undefined) {
          return val
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].value == val) {
            return dict[i].label;
          }
        }
        return val
      },
    },


    created() {
      //this.findDeptTree()

      this.findClassTypes()

      this.dicts = this.$store.state.dict.dicts;
      this.findPage(null);
    },
    watch: {
      $UpLoadFileVisible(to, from) {
        console.log(to);
        console.log(from);
      },
      dialogVisible(to, from) {
        if (this.$refs['dataForm'] !== undefined) {
          this.$refs["dataForm"].resetFields();
        }
      }
    }
  }

</script>

<style scoped>
</style>